package com.project.common.filter;

import com.project.common.entity.SysUsers;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenticateFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        SysUsers user =(SysUsers) session.getAttribute("user");
        String requestURI = request.getRequestURI();
        String homeUrl=request.getContextPath();
        if(requestURI.equals("/login.html") || requestURI.equals("/SysUsers/loginUser")||requestURI.endsWith(".js")||requestURI.endsWith(".css")){
            return true;
        }
        if(user!=null){
            return true;
        }else{
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                response.setHeader("CONTEXTPATH", homeUrl+"/login.html");
                // FORBIDDEN，forbidden。也就是禁止、403
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }else{
                // 如果不是 ajax 请求，则直接跳转即可
                response.sendRedirect(homeUrl+"/login.html");
            }
            return false;
        }
    }
}
